package com.stevin.tool.parser;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mars on 05/11/2018.
 */
public class LogParser {

    private final static String DEFAULT_START_KEY = "开始";
    private final static String DEFAULT_END_KEY = "结束";
    private static boolean isStartLine = false;
    private final static String DEFAULT_SPILT_LINE = " ";
    private static List<String> spiltLines = new ArrayList<>();

    public static void main(String[] args) {
        try {
            URL sampleResource = LogParser.class.getClassLoader().getResource("webflux.log");
            //    URL resultResource = LogTree.class.getClassLoader().getResource("result.log");
            List<String> allLine = Files.readAllLines(Paths.get(sampleResource.getPath()), Charset.defaultCharset());
            //   BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(resultResource.getPath()), StandardOpenOption.APPEND);

            String frontLine = "";

            for (int i = 0; i < allLine.size(); i++) {
                String line = allLine.get(i);
                if (line.length() > i) {
                    frontLine = allLine.get(i + 1);
                    frontLine = frontLine.replaceAll("开始", "  ");
                }

                if (line.contains(DEFAULT_START_KEY)) {
                    line = "  \\____" + line;
                    if (isStartLine) {
                        spiltLines.add(DEFAULT_SPILT_LINE);
                        StringBuilder builder = new StringBuilder(String.join("", spiltLines));
                        builder.append(line);
                        System.out.println(builder.toString());
                    } else {
                        StringBuilder builder = new StringBuilder(String.join("", spiltLines));
                        builder.append(line);
                        System.out.println(builder.toString());
                    }
                    isStartLine = true;
                }

                if (line.contains(DEFAULT_END_KEY)) {
                    line = "       " + line;
                    StringBuilder builder = new StringBuilder(String.join("", spiltLines));
                    builder.append(line);
                    System.out.println(builder.toString());
                    if (spiltLines.size() > 0) {
                        spiltLines.remove(spiltLines.size() - 1);
                    }
                    isStartLine = false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
